<?php

namespace app\common\traits;

trait adminTraits
{
    /**
     * 列表方法
     * @return array
     */
    public function index()
    {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $isPage = $this->request->param('is_page',1); //是否分页
            if($isPage==1){
                $data = $this->pageList();
                return $data;
            }else{
                $data = $this->getlist();
                return $data;
            }
        }
        return $this->fetch($this->request->param('tpl',''));
    }

    /**
     * 分页数据
     */
    public function pageList(){
        $pageSize = $this->request->param('pageSize/d'); //每页多少条
        $pageNumber = $this->request->param('pageNumber/d'); //当前页
        $sortName = $this->request->param('sortName','id'); //排序字段
        $sortOrder = $this->request->param('sortOrder', 'desc'); //升序降序
        $order = [$sortName => $sortOrder];
        $filter = $this->request->param("filter"); //搜索字段值 json
        $op = $this->request->param("op"); //搜索条件 json
        $op = $op ? $op : [];
        $filter = $filter ? $filter : [];
        if(!empty($this->appendQuery)){
            foreach($this->appendQuery as $field){
                $fieldArr = explode('.',$field);
                $value = count($fieldArr)>1 ? $fieldArr[1] : $field;
                $filter[$field] = $this->loginInfo[$value];
                $op[$field] = '=';
            }
        }
        //搜索器配置
        $searchFields = ['common'];//参与搜索信息
        $searchData = [ //默认搜索数据
            'common' => [$filter, $op],
            'sort' => $order,
        ];
        if (method_exists($this, '_pageFilter')) {
            $params = [];
            $this->_pageFilter($params);
            if(!empty($params['custom'])){
                $searchData['common'][0] = array_merge($searchData['common'][0],$params['custom']['filter']);
                $searchData['common'][1] = array_merge($searchData['common'][1],$params['custom']['op']);
            }
            if (!empty($params['fields'])) {
                $searchFields = array_merge($searchFields, $params['fields']);
            }
            if (!empty($params['data'])) {
                $searchData = array_merge($searchData, $params['data']);
            }
        }
        try {
            $data = ['total' => 0, 'rows' => []];
            //分页不需要sort和field
            $countData = $searchData;
            if (isset($countData['sort'])) unset($countData['sort']);
            if (isset($countData['field'])) unset($countData['field']);
            $data['total'] = $this->model->withSearch($searchFields, $countData)->count();
            $data['sql'] = $this->model->getLastSql();
            if ($data['total'] > 0) {
                $list = $this->model->withSearch($searchFields, $searchData)->page($pageNumber, $pageSize)->select();
                //$data['sql'] = $this->model->getLastSql();
                if (method_exists($this->model, '_formatList')) {
                    $list = $this->model->_formatList($list);
                }
                $data['rows'] = $list;
            }
        } catch (\Exception $e) {
            $data = ['total' => 0, 'rows' => [], 'err_msg' => $e->getMessage()];
        }
        return $data;
    }

    /**
     * 不分页数据
     */
    public function getlist(){
        $sortName = $this->request->param('sortName', 'id'); //排序字段
        $sortOrder = $this->request->param('sortOrder', 'desc'); //升序降序
        $order = [$sortName => $sortOrder];
        $filter = $this->request->param("filter"); //搜索字段值 json
        $op = $this->request->param("op"); //搜索条件 json
        $op = $op ? $op : [];
        $filter = $filter ? $filter : [];
        if(!empty($this->appendQuery)){
            foreach($this->appendQuery as $field){
                $fieldArr = explode('.',$field);
                $value = count($fieldArr)>1 ? $fieldArr[1] : $field;
                $filter[$field] = $this->loginInfo[$value];
                $op[$field] = '=';
            }
        }
        //站点ID
        if($this->sessionKey=='site'){
            $filter['site_id'] = $this->loginInfo['site_id'];
            $op['site_id'] = '=';
        }
        //搜索器配置
        $searchFields = ['common'];//参与搜索信息
        $searchData = [ //默认搜索数据
            'common' => [$filter, $op],
            'sort' => $order
        ];
        if (method_exists($this, '_filter')) {
            $params = [];
            $this->_filter($params);
            if(!empty($params['custom'])){
                $searchData['common'][0] = array_merge($searchData['common'][0],$params['custom']['filter']);
                $searchData['common'][1] = array_merge($searchData['common'][1],$params['custom']['op']);
            }
            if (!empty($params['fields'])) {
                $searchFields = array_merge($searchFields, $params['fields']);
            }
            if (!empty($params['data'])) {
                $searchData = array_merge($searchData, $params['data']);
            }
        }
        try {
            $list = $this->model->withSearch($searchFields, $searchData)->select();
            if (method_exists($this->model, '_formatList') && !$list->isEmpty()) {
                $list = $this->model->_formatList($list);
            }
            $data['data'] = $list;
            $data['sql'] = $this->model->getLastSql();
        } catch (\Exception $e) {
            $data['data'] = [];
            $data['err_msg'] = $e->getMessage();
        }
        return $data;
    }
    /**
     * 添加方法
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            try {
                $data = $this->request->param();
                //验证规格
                $validRule = str_replace(["\\model\\", "Model"], ["\\validate\\", 'Validate'], get_class($this->model));
                $this->validate($data, $validRule . '.add');
                $data = $this->appendUserData($data); //追加用户数据
                $info = $this->model->addData($data);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('操作成功！', null, $info);
        }
        return $this->fetch($this->request->param('tpl',''));
    }

    /**
     * 编辑方法
     */
    public function edit()
    {
        $id = $this->request->param('id/d');
        $map[]=['id','=',$id];
        $info = $this->model->getInfo($map);
        if (empty($info)) $this->error('未找到数据！');
        if ($this->request->isAjax()) {
            try {
                $data = $this->request->param();
                //验证规格
                $validRule = str_replace(["\\model\\", "Model"], ["\\validate\\", 'Validate'], get_class($this->model));
                $result = $this->validate($data, $validRule . '.edit');
                if(true !== $result) exception($result);
                $data = $this->appendUserData($data); //追加用户数据
                $info = $this->model->editData($data);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('操作成功！', null, $info);
        }
        $this->assign('info', $info);
        return $this->fetch($this->request->param('tpl',''));
    }

    /**
     * 删除方法
     */
    public function del()
    {
        try {
            $id = $this->request->param('id');
            if(empty($id)) exception('请选择删除数据！');
            $this->model->delData($id);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('操作成功！');
    }

    /**
     * 批量更新数据
     */
    public function multi()
    {
        //ids: 1，3，5
        //params: status:1,is_boss=0
        if ($this->request->has('ids') && $this->request->has('params')) {
            try {
                $ids = $this->request->param('ids');
                $params = $this->request->param('params');
                $this->model->multi($ids, $params);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('操作成功！');
        }
        $this->error('参数错误！');
    }
    /**
     * editable修改内容
     */
    public function editable(){
        header("Content-type: text/html; charset=utf-8");
        try{
            $id = $this->request->param('pk');
            $name = $this->request->param('name');
            $value = $this->request->param('value');
            $this->model->where('id',$id)->setField($name,$value);
        }catch (\Exception $e){
            return response($e->getMessage(),40001);
        }
        return response('操作成功！');
    }
    /**
     * 追加用户数据
     */
    private function appendUserData($data)
    {
        if (!empty($this->appendUserFields)) {
            foreach ($this->appendUserFields as $v) {
                if(isset($data[$v])) continue;
                if($v=='admin_id'){
                    $data['admin_id'] = $this->loginInfo['id'];
                }else{
                    $data[$v] = $this->loginInfo[$v];
                }
            }
        }
        return $data;
    }

}